﻿using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ArienToolkit.Serializer
{
    public class Binary : ISerializer
    {
        public bool Serialize<T>(object obj, string filePath)
        {
            using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                try
                {
                    formatter.Serialize(fileStream, obj);
                }
                catch { return false; }
                finally { fileStream.Close(); }
            }

            return true;
        }

        public T DeSerialize<T>(string filePath)
        {
            T obj;

            using (FileStream stream = new FileStream(filePath, FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                obj = (T)formatter.Deserialize(stream);
            }

            return obj;
        }
    }
}
